package pers.ervinse.shoppingmall;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.google.gson.Gson;

import java.io.IOException;

import pers.ervinse.shoppingmall.domain.User;
import pers.ervinse.shoppingmall.utils.OkhttpUtils;
import pers.ervinse.shoppingmall.utils.PropertiesUtils;
import pers.ervinse.shoppingmall.viewmodel.UserResponse;
import pers.ervinse.shoppingmall.viewmodel.UserViewModel;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = LoginActivity.class.getSimpleName();
    private static final int REGISTER_REQUEST_CODE = 1;

    private Context mContext;
    private EditText login_name_et, login_password_et;
    private Button user_register_btn, login_btn;

    private String userName, userPassword;
    private UserViewModel userViewModel; // 声明 UserViewModel

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = this;

        // 初始化 ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        login_name_et = findViewById(R.id.login_name_et);
        login_password_et = findViewById(R.id.login_password_et);
        user_register_btn = findViewById(R.id.user_register_btn);
        login_btn = findViewById(R.id.login_btn);

        initListener();
    }

    private void initListener() {
        // 登录按钮监听事件
        login_btn.setOnClickListener(v -> {
            Log.i(TAG, "登录按钮响应事件");

            // 获取当前输入框内容
            userName = login_name_et.getText().toString();
            userPassword = login_password_et.getText().toString();

            login();
        });

        // 注册按钮监听事件
        user_register_btn.setOnClickListener(v -> {
            Log.i(TAG, "前往注册页面事件");

            // 跳转注册页面
            Intent intent = new Intent(mContext, RegisterActivity.class);
            startActivityForResult(intent, REGISTER_REQUEST_CODE);
        });
    }

    private void login() {
        new Thread() {
            @Override
            public void run() {
                Log.i(TAG, "进入请求登录线程");

                Gson gson = new Gson();
                User user = new User(userName, userPassword);
                String userJson = gson.toJson(user);
                Log.i(TAG, "登录请求json:" + userJson);
                String responseJson = null;

                try {
                    // 发送登录请求
                    String url = PropertiesUtils.getUrl();
                    responseJson = OkhttpUtils.doPost(url + "/users/login", userJson);
                    Log.i(TAG, "登录请求响应json:" + responseJson);

                    // 解析响应为 UserResponse 对象
                    UserResponse loginResponse = gson.fromJson(responseJson, UserResponse.class);

                    if (loginResponse != null && loginResponse.isStatus()) {
                        Log.i(TAG, "登录成功，用户信息:" + loginResponse.getUserData());

                        String name = loginResponse.getUserData().getName();
                        String avatarUrl = loginResponse.getUserData().getAvatarUrl();
                        int sex = loginResponse.getUserData().getSex();

                        // 回传用户数据到主页面
                        Intent intent = new Intent();
                        intent.putExtra("userName", name);
                        intent.putExtra("avatarUrl", avatarUrl);  // 传递头像 URL
                        intent.putExtra("sex", sex);
                        setResult(RESULT_OK, intent);
                        finish();  // 返回到 UserFragment
                    } else {
                        Log.i(TAG, "登录失败，状态: " + (loginResponse != null ? loginResponse.isStatus() : "null"));
                        Looper.prepare();
                        Toast.makeText(mContext, "登录失败,用户名或密码错误", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Looper.prepare();
                    Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        }.start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REGISTER_REQUEST_CODE && resultCode == RESULT_OK) {
            // 获取注册后的数据
            userName = data.getStringExtra("userName");
            userPassword = data.getStringExtra("userPassword");
            Log.i(TAG, "用户注册数据回传: userName = " + userName + ", userPassword = " + userPassword);
            login();  // 自动登录
        }
    }
}
